package com.fingard.dsp.bank.directbank.shie01;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.shie.openapi.dto.ResponseDto;

public class SHIE01Transaction extends SHIE01Base implements ITransaction {
	@Override
	public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
		RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
		String tmpRespCode = "";
		String tmpRespInfo = "";
		retAts.writeStart();

		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_req7516.actNum, "*");
			if (actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath)) {
				retAts.writeRespCode("-1");
				if (actItem == null) {
					retAts.writeRespInfo("未找到账号" + p_req7516.actNum + "的商户配置信息");
				} else {
					retAts.writeRespInfo("账号" + p_req7516.actNum + "的商户证书文件不存在");
				}
				return retAts;
			}

			Calendar tmpCalendarFrom = Calendar.getInstance();
			tmpCalendarFrom.setTime(p_req7516.getDateFrom());

			Calendar tmpCalendarTo = Calendar.getInstance();
			tmpCalendarTo.setTime(p_req7516.getDateTo());

			int tmpIntDateFrom = 0;
			int tmpIntDateTo = 0;
			// 按自然月循环查询
			while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
				Calendar tmpClndrStepTo = Calendar.getInstance();
				tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
				// 判断是否跨月
				if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
					// 跨月则设置为月末
					tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo
							.getActualMaximum(Calendar.DAY_OF_MONTH));
				} else {
					tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
				}

				// 服务代码
				String serviceCode = "account.orderDetailsQuery";

				Map<String, Object> bizContent = new HashMap<String, Object>();

				// 商户代码
				bizContent.put("comCode", actItem.inMerchantId);
                bizContent.put("custId", p_req7516.actNum);
				bizContent.put("startDate",Format.Date8Format.format(tmpCalendarFrom.getTime()));
				bizContent.put("endDate", Format.Date8Format.format(tmpClndrStepTo.getTime()));
				bizContent.put("pageNo", 1);
				bizContent.put("pageSize", 1000);

				ResponseDto responseDto = sendToSHIE(actItem, serviceCode, bizContent);

				// 解析银行返回
				String tmpbackCode = responseDto.getResponseCode();
				if ("0000".equals(tmpbackCode)) {
					JSONObject respBizContent = JSON.parseObject(responseDto.getBizContent());

					String msgCode = respBizContent.getString("msgCode");
					if ("0000".equals(msgCode)) {
						if (respBizContent.getString("rtNum").equals("0"))// 返回0表示无记录
						{
							tmpRespCode = "-1";
							tmpRespInfo = "银行返回记录为空！";
							break;
						}
						
						JSONArray respBodyJson = JSONArray.parseArray(respBizContent.getString("details"));
						if (respBodyJson.size() > 0) {
							for (int i = 0; i < respBodyJson.size(); i++) {
								JSONObject jsonDetail = respBodyJson.getJSONObject(i);
								RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
								
								Date date = new SimpleDateFormat("yyyyMMddHHmmss").parse(jsonDetail.getString("orderTime"));
								tmpRetDetail.actArea = p_req7516.actArea;
								tmpRetDetail.cur = p_req7516.actCur;
								tmpRetDetail.actNum = p_req7516.actNum;
                                tmpRetDetail.recAccNum = jsonDetail.getString("bankCardNo");
								tmpRetDetail.accBal = "0.00";
								tmpRetDetail.tranDate = Format.Date10Format.format(date);
								tmpRetDetail.tranTime = Format.DateTimeFormat.format(date);
								tmpRetDetail.valueDate = Format.DateTimeFormat.format(date);
								tmpRetDetail.postTimestamp = Format.DateTime14Format.format(date);
								tmpRetDetail.askNumber = jsonDetail.getString("orderNo");
								tmpRetDetail.tranAmt = StringHelper.amountDivide100(jsonDetail.getString("amount"));
								tmpRetDetail.recAccName = jsonDetail.getString("bankCardName");
								tmpRetDetail.recAccBank = jsonDetail.getString("tranBank");
								tmpRetDetail.comment = jsonDetail.getString("optional");
								String cdFlag = jsonDetail.getString("drCrFlag");
								if ("DR".equals(cdFlag)) {
									tmpRetDetail.cdFlag = "1";
								} else {
									tmpRetDetail.cdFlag = "2";
								}
								tmpRetDetail.abstr = jsonDetail.getString("orderNo");

								retAts.writeRetDetail(tmpRetDetail);
							}
						} else {
							tmpRespCode = "-1";
							tmpRespInfo = "返回不符合预期!";
						}
					} else {
						// "查询失败"
						tmpRespCode = "-1";
						tmpRespInfo = "该帐户没有所要的流水！错误编码：" + msgCode;
					}
				} else {
					if ("9105".equals(tmpRespCode)) {
						tmpRespCode = "0";
						tmpRespInfo = responseDto.getResponseDesc();
					} else {
						tmpRespCode = "-1";
						tmpRespInfo = responseDto.getResponseDesc();
					}
				}

				tmpCalendarFrom = tmpClndrStepTo;
				tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
				tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
				tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
			}
		} catch (Exception e) {
			tmpRespCode = "-1";
			tmpRespInfo = e.getMessage();
			e.printStackTrace();
		}

		if (tmpRespCode.equals("-1")) {
			retAts = new RetAtsTrans(p_req7516.reqHeader);
			retAts.writeStart();
			retAts.writeRespCode(tmpRespCode);
			retAts.writeRespInfo(tmpRespInfo);
		} else if (retAts.getWrittenRdCount() == 0) {
			retAts.writeRespCode("0");
			retAts.writeRespInfo("交易为空");
		}

		retAts.writeEnd();
		return retAts;
	}

	/**
	 * 今日明细查询 7515
	 */
	@Override
	public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
		Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);

		String tmpStrToday = Format.Date8Format.format(new Date());

		tmpReq7516.actArea = p_req7515.actArea;
		tmpReq7516.actCur = p_req7515.actCur;
		tmpReq7516.actNum = p_req7515.actNum;
		tmpReq7516.dateFrom = tmpStrToday;// 设置开始时间和结束时间都为当天
		tmpReq7516.dateTo = tmpStrToday;

		return d_7516_HisTrans(tmpReq7516);
	}
}
